package elm.example.controller;

/*
    classDescription:管理员控制类，实现管理员信息的相关服务逻辑
*/

import elm.example.dao.IAdminDao;
import elm.example.po.Admin;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;


@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/admin")
@Tag(name = "管理员信息相关服务")
public class AdminController {

    @Resource
    private IAdminDao adminDao;

    @Operation(summary = "管理员注册")
    @Parameters({
            @Parameter(name="name" ,description = "用户名"),
            @Parameter(name="pwd" ,description = "密码")
    })
    @PostMapping("/register")
    public String register(@RequestParam(value = "name") String adminName, @RequestParam(value = "pwd") String password) {
        if (adminDao.findAdminByAdminName(adminName).isPresent()) {
            return "用户名已存在";
        }
        Admin a = new Admin();
        a.setAdminName(adminName);
        a.setPassword(password);
        adminDao.save(a);
        return "注册成功";
    }

    @Operation(summary = "管理员登录")
    @Parameters({
            @Parameter(name="name" ,description = "用户名"),
            @Parameter(name="pwd" ,description = "密码")
    })
    @PostMapping(value = "/login")
    public String login(@RequestParam(value = "name") String adminName, @RequestParam(value = "pwd") String password) {
        Optional<Admin> loginUser = adminDao.findAdminByAdminNameAndPassword(adminName, password);
        return loginUser.isPresent() ? "登录成功" : "用户名或密码错误";
    }

    @Operation(summary = "获取所有管理员信息")
    @GetMapping(value = "/findAll")
    public List<Admin> findAllAdmins() {
        return StreamSupport.stream(adminDao.findAll().spliterator(),false)
                .collect(Collectors.toList());
    }

    @Operation(summary = "根据ID删除管理员")
    @Parameter(name = "id", description = "adminId")
    @DeleteMapping("/deleteAdmin")
    public String delete(@RequestParam(value = "id") Integer adminId) {
        adminDao.deleteById(adminId);
        return "删除成功";
    }

    @Operation(summary = "更新管理员信息")
    @Parameter(name="admin",description = "管理员信息JSON格式")
    @PutMapping("/update")
    public String update(@RequestBody Admin admin) {
        adminDao.save(admin);
        return "更新成功";
    }
}
